package me.numark.fragments;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import me.numark.R;
import me.numark.model.User;
import me.numark.net.BaseResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.Settings;
import me.numark.view.CircleImageView;


public class UsersListFragment extends Fragment implements AdapterView.OnItemClickListener,
        PullToRefreshBase.OnRefreshListener2, View.OnClickListener {


    private static final String ARG_USER_UID = "uid";
    private static final String ARG_USER_NICK = "nick";
    private static final String ARG_TYPE = "type";
    public static final int TYPE_FANS = 0;
    public static final int TYPE_FOLLOWERS = 1;

    private String mUid;
    private String mNick;
    private int mType;
    ArrayList<User> mUsersList;


    PullToRefreshListView mList;
    UsersAdapter mAdapter = new UsersAdapter();

    public static UsersListFragment newInstance(String uid, String nick, int type) {
        UsersListFragment fragment = new UsersListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_USER_UID, uid);
        args.putString(ARG_USER_NICK, nick);
        args.putInt(ARG_TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    public UsersListFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mUid = getArguments().getString(ARG_USER_UID);
            mNick = getArguments().getString(ARG_USER_NICK);
            mType = getArguments().getInt(ARG_TYPE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_simple_list, container, false);
        TextView title = (TextView) view.findViewById(R.id.title);
        String titleText = getString(mType == 0 ? R.string.fans_title : R.string.followers_title, mNick);
        title.setText(titleText);
        view.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        mList = (PullToRefreshListView) view.findViewById(R.id.ptr_list);
        mList.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        mList.setOnRefreshListener(this);
        mList.setAdapter(mAdapter);
        mList.setState(PullToRefreshBase.State.INIT_REFRESHING, true);
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        String url = String.format(mType == TYPE_FANS ? NetworkConstants.FANS_URL : NetworkConstants.FOLLOWS_URL, mUid);
        Map<String, String> body = new LinkedHashMap<String, String>();
        body.put("uid", Settings.getUid());
        url = url + "?" + GsonRequest.getQueryString(body);
        GsonRequest<UsersListResponse> request = new GsonRequest<UsersListResponse>(url,
                Request.Method.POST, UsersListResponse.class, true, null,
                new Response.Listener<UsersListResponse>() {
                    @Override
                    public void onResponse(UsersListResponse response) {
                        if (!response.ret) {
                            finishLoading();
                            return;
                        }
                        mUsersList = new ArrayList<User>();
                        mUsersList.addAll(response.data);
                        mAdapter.notifyDataSetChanged();
                        finishLoading();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), R.string.common_failed, Toast.LENGTH_SHORT).show();
                finishLoading();
            }
        });
        NetworkHelper.getInstance().getRequestQueue().add(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {

    }

    private void finishLoading() {
        mList.postDelayed(new Runnable() {
            @Override
            public void run() {
                mList.onRefreshComplete();
            }
        }, 100);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.check_box: {
                User user = (User) v.getTag();
                doFollow(user);
            }
            break;
        }
    }

    private void doFollow(final User user) {
        String baseUrl = user.is_follow ? NetworkConstants.UNFOLLOW_URL : NetworkConstants.FOLLOW_URL;
        String url = String.format(baseUrl, Settings.getUid(), user.uid);
        GsonRequest<BaseResponse> request = new GsonRequest<BaseResponse>(url, Request.Method.GET,
                BaseResponse.class, true, null, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.ret) {
                    user.is_follow = !user.is_follow;
                    mList.getRefreshableView().invalidateViews();
                } else {
                    Toast.makeText(getActivity(), response.msg, Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), R.string.common_failed, Toast.LENGTH_SHORT).show();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private class UsersListResponse {

        boolean ret;

        List<User> data;
    }

    private class UsersAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mUsersList == null)
                return 0;
            return mUsersList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = getActivity().getLayoutInflater()
                        .inflate(R.layout.friend_list_item, parent, false);
            }
            CircleImageView avatar = (CircleImageView) view.findViewById(R.id.avatar);
            TextView name = (TextView) view.findViewById(R.id.name);
            TextView desc = (TextView) view.findViewById(R.id.desc);
            TextView fansCount = (TextView) view.findViewById(R.id.fans_count);
            TextView signature = (TextView) view.findViewById(R.id.signature);
            ImageView checkBox = (ImageView) view.findViewById(R.id.check_box);
            User user = mUsersList.get(position);
            if (!TextUtils.isEmpty(user.pic)) {
                Picasso.with(getActivity()).load(user.pic).into(avatar);
            }
            name.setText(user.nick);
            signature.setText(user.des);
            desc.setVisibility(View.GONE);
            fansCount.setText(getString(R.string.fans_count) + user.fans);
            if (user.is_follow) {
                if (user.is_fans)
                    checkBox.setImageResource(R.drawable.both_follow);
                else
                    checkBox.setImageResource(R.drawable.remove_follow);
            } else {
                checkBox.setImageResource(R.drawable.add_follow);
            }
            checkBox.setTag(user);
            checkBox.setOnClickListener(UsersListFragment.this);
            return view;
        }
    }
}
